package com.health.manage.token;

import com.alibaba.fastjson.JSON;
import com.health.manage.pojo.entity.User;
import com.health.manage.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截请求，设置当前操作者
 **/
@Slf4j
@Component
public class OperatorAwareInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private IUserService userService;

    public static final String SESSION_USER = "X-Token";

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler){
        try {
            OperatorAware.clear(); // MUST clear
            String token = req.getHeader(SESSION_USER);
            if(StringUtils.isNotEmpty(token)){
                AuthToken authToken = JWTTokenUtil.buildAuthToken(token);
                CurrentUser currentUser = new CurrentUser();
                currentUser.setUserName(authToken.getUserName());
                currentUser.setId(authToken.getUserId());
                Long userId = authToken.getUserId();
                User user = userService.getById(userId);
                if(user != null){
                    currentUser.setRole(user.getRole());
                    currentUser.setPhone(user.getPhone());
                }
                OperatorAware.setCurrentUser(currentUser);
                System.out.println("currentUser: {}"+JSON.toJSONString(currentUser));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

}
